use deno_runtime::deno_core::serde::Serialize;
use serde::Deserialize;

#[derive(Debug, Serialize, Deserialize)]
pub struct JsEngineResult {
    pub code: u32,
    pub msg: String,
    pub data: Option<serde_json::Value>,
}

impl ToString for JsEngineResult {
    fn to_string(&self) -> String {
        serde_json::to_string(self).expect("JsEngineResult to_string error")
    }
}

#[derive(Debug, Clone)]
pub enum JsEngineError {
    E(String),
}

impl From<JsEngineError> for String {
    fn from(value: JsEngineError) -> Self {
        match value {
            JsEngineError::E(err) => err.to_string(),
        }
    }
}

impl std::fmt::Display for JsEngineError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JsEngineError::E(err) => write!(f, "{}", err),
        }
    }
}

impl From<String> for JsEngineError {
    fn from(value: String) -> Self {
        JsEngineError::E(value)
    }
}

impl From<std::io::Error> for JsEngineError {
    fn from(value: std::io::Error) -> Self {
        JsEngineError::from(value.to_string())
    }
}

impl From<serde_json::Error> for JsEngineError {
    fn from(value: serde_json::Error) -> Self {
        JsEngineError::from(value.to_string())
    }
}

impl From<deno_runtime::deno_core::anyhow::Error> for JsEngineError {
    fn from(value: deno_runtime::deno_core::anyhow::Error) -> Self {
        JsEngineError::from(value.to_string())
    }
}

impl From<deno_runtime::deno_core::serde_v8::Error> for JsEngineError {
    fn from(value: deno_runtime::deno_core::serde_v8::Error) -> Self {
        JsEngineError::from(value.to_string())
    }
}
